package com.ryl.yomall.order.listener;


import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.ryl.yomall.model.enums.PaymentWay;
import com.ryl.yomall.model.enums.ProcessStatus;
import com.ryl.yomall.model.order.OrderDetail;
import com.ryl.yomall.model.order.OrderInfo;
import com.ryl.yomall.order.config.DeadLetterMQConfig;
import com.ryl.yomall.order.service.OrderService;
import com.ryl.yomall.rabbitmq.constant.MQConstant;
import com.ryl.yomall.rabbitmq.service.RabbitService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @Date 14:17
 * @Author ryl
 */
@Component
public class OrderConsumer {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitService rabbitService;
    //取消订单
    @RabbitListener(queues = DeadLetterMQConfig.QUEUE_ORDER_CANCEL2)
    public void orderCancel(Long orderId,Channel channel,Message message){

        System.out.println ("收到消息orderId:"+orderId );
        System.out.println ("接收到的时间:"+ Calendar.getInstance ().getTime () );
        try {
            orderService.cancelOrder(orderId);
            channel.basicAck ( message.getMessageProperties ().getDeliveryTag (),false );
        } catch (IOException e) {
            e.printStackTrace ( );
        }
    }
    //支付成功,更新订单
    @RabbitListener(bindings = @QueueBinding ( value = @Queue(value = MQConstant.QUEUE_PAYMENT_PAY,durable = "true"),
    exchange = @Exchange(value = MQConstant.EXCHANGE_DIRECT_PAYMENT_PAY),key = {MQConstant.ROUTING_PAYMENT_PAY}))
    public void paySuccess(Long orderId, Message message, Channel channel){
        if (null != orderId){
            //防止重复消费
            OrderInfo orderInfo = orderService.getById(orderId);
            if(null != orderInfo && orderInfo.getOrderStatus().equals( ProcessStatus.UNPAID.getOrderStatus().name())) {
                // 支付成功！ 修改订单状态为已支付
                orderService.updateOrderStatus(orderId, ProcessStatus.PAID);

            }
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace ( );
        }

    }


}
